from .. import db
from datetime import datetime

class OilFacility(db.Model):
    """油料设施模型"""
    __tablename__ = 'oil_facilities'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    facility_type = db.Column(db.String(50), nullable=False)  # import(进口), refinery(炼油), storage(存储), airport(机场)
    capacity = db.Column(db.Float, nullable=False)  # 容量/产能（万吨）
    region = db.Column(db.String(50), nullable=False)  # 区域：taipei, taichung, tainan, hualien, kaohsiung
    latitude = db.Column(db.Float, nullable=False)  # 纬度
    longitude = db.Column(db.Float, nullable=False)  # 经度
    airport_id = db.Column(db.Integer, db.ForeignKey('airports.id'), nullable=True)  # 对应机场ID，可为空
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)

    # 关系
    outgoing_relations = db.relationship('OilSupplyRelation', foreign_keys='OilSupplyRelation.source_id', backref='source_facility', lazy='dynamic')
    incoming_relations = db.relationship('OilSupplyRelation', foreign_keys='OilSupplyRelation.target_id', backref='target_facility', lazy='dynamic')
    
    def __repr__(self):
        return f'<OilFacility {self.name} - {self.facility_type}>'
    
    def get_category(self):
        """获取设施类别编号，对应于前端分类"""
        category_map = {
            'import': 0,    # 原油进口设施
            'refinery': 1,  # 炼油厂
            'storage': 2,   # 区域存储油库
            'airport': 3    # 机场油库
        }
        return category_map.get(self.facility_type, 0)
    
    def to_dict(self):
        """转换为字典表示"""
        return {
            'id': self.id,
            'name': self.name,
            'facility_type': self.facility_type,
            'capacity': self.capacity,
            'region': self.region,
            'latitude': self.latitude,
            'longitude': self.longitude,
            'airport_id': self.airport_id,
            'category': self.get_category(),
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def get_color(self):
        """获取设施颜色（用于前端显示）"""
        color_map = {
            'import': '#1976D2',    # 蓝色 - 原油进口设施
            'refinery': '#D32F2F',  # 红色 - 炼油厂
            'storage': '#FFA000',   # 橙色 - 区域存储油库
            'airport': '#388E3C'    # 绿色 - 机场油库
        }
        return color_map.get(self.facility_type, '#9E9E9E') 